package com.sunny.myproject.core.base.service;

import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;

import com.sunny.myproject.core.base.dao.DAOUtil;
import com.sunny.myproject.core.base.dao.HibernateSessionFactory;

public class BaseServiceImpl<T> extends HibernateSessionFactory{

	@SuppressWarnings("unchecked")
	protected Class<T> persistentClass = (Class<T>) DAOUtil.getTypeArguments(
			BaseServiceImpl.class, this.getClass()).get(0);
	private DetachedCriteria detachedcriteria;
	
	public void save(T t) {
		this.getHibernateTemplate().saveOrUpdate(t);
	}

	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}

	public void deleteByIds(Long[] ids) {
		for (Long serializable : ids) {
			deleteById(serializable);
		}		
	}
	
	public void deleteById(Long id) {
		this.getHibernateTemplate().delete(findById(id));		
	}

	@SuppressWarnings("unchecked")
	public List<T> list(List<Criterion> criterions) {
		detachedcriteria = DetachedCriteria.forClass(persistentClass);
		for (Criterion criterion : criterions) {
			detachedcriteria.add(criterion);
		}
		return this.getHibernateTemplate().findByCriteria(detachedcriteria);
	}

	@SuppressWarnings("unchecked")
	public List<T> find(List<Criterion> criterions, int firstResult,
			int maxResults) {
		detachedcriteria = DetachedCriteria.forClass(persistentClass);
		for (Criterion criterion : criterions) {
			detachedcriteria.add(criterion);
		}
		/*for (Projection projection : projections) {
			detachedcriteria.setProjection(projection);
		}
		for (Order order : orders) {
			detachedcriteria.addOrder(order);
		}*/
		return this.getHibernateTemplate().findByCriteria(detachedcriteria,
				firstResult, maxResults);
	}

	public Integer num(List<Criterion> criterions) {
		detachedcriteria = DetachedCriteria.forClass(persistentClass);
		for (Criterion criterion : criterions) {
			detachedcriteria.add(criterion);
		}
		detachedcriteria.setProjection(Projections.count("id"));
		@SuppressWarnings("unchecked")
		List<Object> objects = this.getHibernateTemplate().findByCriteria(
				detachedcriteria);
		return Integer.parseInt(objects.get(0).toString());
	}

	public T findById(Long id) {
		detachedcriteria = DetachedCriteria.forClass(persistentClass);
		return this.getHibernateTemplate().get(persistentClass, id);
	}

	public Object queryHql(String hql){
		return this.getHibernateTemplate().find(hql);
	}
}
